<template>
  <el-dialog title="批量导入" v-model="dialogVisible" width="500px" top="400px">
    <el-upload drag class="upload-demo" :headers="headers" action="http://localhost:8080/bydspecialPoject/upload"
      :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3"
      :on-success="handleSuccess" :on-exceed="handleExceed" :on-error="handleError" :file-list="fileList">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">
        只能上传xls/xlsx文件，且不超过50MB
      </div>
    </el-upload>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage, ElUploadFile } from 'element-plus';
import { getToken } from '@/utils/auth';

const dialogVisible = ref(false);
const fileList = ref<ElUploadFile[]>([]);
const headers = ref<Record<string, string>>({
  authorization: `Bearer ${getToken()}`
});

const emit = defineEmits(['refresh']);

const showDialog = () => {
  dialogVisible.value = true;
};

const handleRemove = (file: ElUploadFile, fileList: ElUploadFile[]) => {
  console.log(file, fileList);
};

const handlePreview = (file: ElUploadFile) => {
  console.log(file);
};

const handleExceed = (files: ElUploadFile[], fileList: ElUploadFile[]) => {
  ElMessage.warning(
    `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
  );
};

const handleSuccess = (response: any) => {
  if (response.code === 200) {
    ElMessage.success('上传成功');
    emit('refresh');
    dialogVisible.value = false;
  } else {
    fileList.value.splice(fileList.value.length - 1, 1);
    ElMessage.error(response.msg);
  }
};

const handleError = (error: any) => {
  ElMessage.error('上传失败');
  console.error(error);
};

const beforeRemove = (file: ElUploadFile) => {
  return ElMessage.confirm(`确定移除 ${file.name}？`);
};

defineExpose({ showDialog });
</script>

<style scoped>
.upload-demo {
  text-align: center;
}
</style>
